package com.security.brows.ui

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.CountDownTimer
import android.text.format.Formatter
import android.webkit.WebView
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.viewModels
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.spring
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.BottomSheetScaffoldState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.SheetState
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Text
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.material3.rememberStandardBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.zIndex
import androidx.core.app.ShareCompat
import coil.compose.AsyncImage
import com.hub.videobrowsdownload.BrowsApplication
import com.hub.videobrowsdownload.BrowsM3U8Helper
import com.hub.videobrowsdownload.BrowsMyWebView
import com.hub.videobrowsdownload.BrowsTabWebViewModel
import com.hub.videobrowsdownload.BrowsVideoPrepare
import com.hub.videobrowsdownload.R
import com.security.brows.base.SecurityBaseActivity
import com.security.brows.room.BrowsRoomHelper
import com.security.brows.room.BrowsWebFavoriteBean
import com.security.brows.values.SecurityBrowsColorsScheme
import com.security.brows.values.SecurityBrowsDrawable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.roundToInt

@OptIn(ExperimentalMaterial3Api::class)
class SecurityBrowsTabWebActivity : SecurityBaseActivity() {
    companion object {
        fun start(context: Context, url: String?) {
            context.startActivity(Intent(context, SecurityBrowsTabWebActivity::class.java).apply {
                putExtra("initUrl", url)
            })
        }

        fun startSafari(context: Context, url: String) {
            try {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                context.startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun sendEmail(context: Context, email: String, subject: String, message: String) {
            try {
                val intent = Intent(Intent.ACTION_SENDTO).apply {
                    data = Uri.parse("mailto:$email")
                    putExtra(Intent.EXTRA_SUBJECT, subject)
                    putExtra(Intent.EXTRA_TEXT, message)
                }

                context.startActivity(intent)
            } catch (e: Exception) {
                Toast.makeText(context, "Thanks", Toast.LENGTH_SHORT).show()
            }
        }

    }

    var hasToastDoNotCloseWhenDownloading = false
    val tabWebViewModel: BrowsTabWebViewModel by viewModels()

    var countDownTimer: CountDownTimer? = null
    var isTimerStart = false
    var webView: WebView? = null
    var initUrl = ""

    override fun preContent() {
        super.preContent()
        val s = intent.getStringExtra("initUrl")
        initUrl = if (!s.isNullOrEmpty()) {
            if (s.startsWith("http://") || s.startsWith("https://")) {
                s.trim()
            } else {
                "https://www.google.com/search?q=${s.trim()}"
            }
        } else {
            "https://www.google.com"
        }
        tabWebViewModel.currentWebUrl.value = initUrl
    }

    @Composable
    override fun ComposeContent(
        isDarkTheme: Boolean,
        colorsScheme: SecurityBrowsColorsScheme,
        drawableScheme: SecurityBrowsDrawable
    ) {
        val scope = rememberCoroutineScope()
        val downloadSelectList = remember {
            mutableStateListOf<BrowsVideoPrepare>()
        }
        val videoList = tabWebViewModel.findVideoList.observeAsState()
        val rememberBottomSheetScaffoldState = rememberBottomSheetScaffoldState(
            rememberStandardBottomSheetState(
                initialValue = SheetValue.Hidden, skipHiddenState = false
            )
        )
        Column(
            Modifier
                .fillMaxSize()
                .background(colorsScheme.browsBg)
        ) {
            AppToolbar(drawableScheme, colorsScheme)
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {
                BoxWebView(initUrl)

                DownloadFloatingButton(
                    drawableScheme,
                    videoList,
                    rememberBottomSheetScaffoldState.bottomSheetState
                )

            }
        }

        if (!videoList.value.isNullOrEmpty()) {
            BottomSheetScaffoldCompose(
                rememberBottomSheetScaffoldState,
                videoList,
                colorsScheme,
                drawableScheme,
                downloadSelectList
            )
        }

        BackHandler(true) {
            if (rememberBottomSheetScaffoldState.bottomSheetState.targetValue == SheetValue.Expanded) {
                scope.launch {
                    rememberBottomSheetScaffoldState.bottomSheetState.hide()
                }
            } else if (f()) {

            } else {
                finish()
            }

        }


    }

    @Composable
    private fun BoxScope.DownloadFloatingButton(
        drawableScheme: SecurityBrowsDrawable,
        videoList: State<MutableList<BrowsVideoPrepare>?>,
        rememberBottomSheetScaffoldState: SheetState
    ) {
        val openAlertDialog = remember { mutableStateOf(false) }
        var offset by remember { mutableStateOf(Offset.Zero) }
        val shake = remember { Animatable(0f) }
        var trigger by remember { mutableStateOf(false) }
        val scope = rememberCoroutineScope()
        LaunchedEffect(videoList.value) {
            try {
                if (!videoList.value.isNullOrEmpty()) {
                    openAlertDialog.value = false
                    if (!trigger) {
                        trigger = true
                        for (i in 0..10) {
                            when (i % 2) {
                                0 -> shake.animateTo(5f, spring(stiffness = 100_000f))
                                else -> shake.animateTo(-5f, spring(stiffness = 100_000f))
                            }
                        }
                        shake.animateTo(0f)
                    }
                } else {
                    rememberBottomSheetScaffoldState.hide()
                    trigger = false
                }
            } catch (e: Exception) {
                trigger = false
                e.printStackTrace()
            }
        }
        FloatingActionButton(
            onClick = {
                if (!videoList.value.isNullOrEmpty()) {
                    scope.launch {
                        rememberBottomSheetScaffoldState.expand()
                    }
                } else {
                    openAlertDialog.value = true
                    scope.launch {
                        rememberBottomSheetScaffoldState.hide()
                    }
                }
            },
            modifier = Modifier
                .offset {
                    IntOffset(offset.x.toInt() + shake.value.roundToInt(), offset.y.toInt())
                }
                .padding(horizontal = 38.dp, vertical = 26.dp)
                .align(Alignment.BottomEnd)
                .size(68.dp)
                .pointerInput(Unit) {
                    detectDragGestures(onDrag = { change, _ ->
                        offset += change.positionChange()
                    })
                },
            shape = CircleShape
        ) {
            Image(
                painter = painterResource(id = if (videoList.value.isNullOrEmpty()) drawableScheme.download_n else drawableScheme.download),
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.FillBounds
            )
        }

        if (openAlertDialog.value) {
            AlertDialogExample(
                onDismissRequest = { openAlertDialog.value = false },
                onConfirmation = {
                    openAlertDialog.value = false
                    if (tabWebViewModel.currentWebUrl.value?.contains(".youtube.") == true) {
                        Toast.makeText(
                            this@SecurityBrowsTabWebActivity,
                            "This page doesn't support. Try another one.",
                            Toast.LENGTH_SHORT
                        )
                            .show()
                    } else {
                        try {
                            ShareCompat.IntentBuilder(this@SecurityBrowsTabWebActivity)
                                .setType("text/plain")
                                .setChooserTitle("Share website via")
                                .setText(tabWebViewModel.currentWebUrl.value)
                                .startChooser();
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                },
                dialogTitle = "NOT FOUND",
                dialogText = "Video not found, would you like to report this webpage?"
            )
        }
    }

    @Composable
    private fun AppToolbar(
        drawableScheme: SecurityBrowsDrawable,
        colorsScheme: SecurityBrowsColorsScheme
    ) {
            val downloadingSize = BrowsApplication.browsMyViewModel.downloadingTaskSize.observeAsState()
        val showPopupMenu = remember {
            mutableStateOf(false)
        }
        val scope = rememberCoroutineScope()
        val title = tabWebViewModel.webTitle.observeAsState()
        Box(
            Modifier
                .fillMaxWidth()
                .height(60.dp)
                .background(colorsScheme.browsBg)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .width(50.dp)
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        onBackPressed()
                    }
            ) {
                Image(
                    painter = painterResource(id = drawableScheme.back),
                    contentDescription = null,
                    modifier = Modifier
                        .align(
                            Alignment.Center
                        )
                        .size(20.dp)
                )
            }

            Text(
                text = title.value ?: "",
                color = colorsScheme.homeTitle,
                fontSize = 20.sp,
                modifier = Modifier
                    .padding(horizontal = 100.dp)
                    .align(Alignment.Center),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )


            Box(
                modifier = Modifier
                    .align(Alignment.CenterEnd)
                    .padding(end = 50.dp)
                    .fillMaxHeight()
                    .width(50.dp)
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        SecurityBrowsHomeActivity.start(this@SecurityBrowsTabWebActivity, 1)
                    }
            ) {
                if ((downloadingSize.value ?: 0) > 0) {
                    Box(
                        modifier = Modifier
                            .align(Alignment.Center)
                    ) {
                        Text(
                            text = downloadingSize.value.toString(),
                            fontSize = 10.sp,
                            color = colorsScheme.homeTable,
                            modifier = Modifier.align(Alignment.Center)
                        )
                        CircularProgressIndicator(modifier = Modifier.size(30.dp), strokeCap = StrokeCap.Round, color = colorsScheme.homeTable, strokeWidth = 1.dp)
                    }
                } else {
                    Image(
                        painter = painterResource(id = drawableScheme.tab_down_n),
                        contentDescription = null,
                        modifier = Modifier
                            .align(
                                Alignment.Center
                            )
                            .size(30.dp),
                        contentScale = ContentScale.Companion.FillBounds
                    )
                }
            }

            Box(
                modifier = Modifier
                    .align(Alignment.CenterEnd)
                    .fillMaxHeight()
                    .width(50.dp)
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        showPopupMenu.value = true
                    }
            ) {
                Image(
                    painter = painterResource(id = drawableScheme.menu_more),
                    contentDescription = null,
                    modifier = Modifier
                        .align(
                            Alignment.Center
                        )
                        .size(20.dp)
                )
            }

            if (showPopupMenu.value) {

                PopCompose(showPopupMenu, scope, drawableScheme, colorsScheme)
            }
        }

        Spacer(
            modifier = Modifier
                .fillMaxWidth()
                .height(12.dp)
                .background(colorsScheme.homeTitleSpace)
        )
    }

    @Composable
    private fun PopCompose(
        showPopupMenu: MutableState<Boolean>,
        scope: CoroutineScope,
        drawableScheme: SecurityBrowsDrawable,
        colorsScheme: SecurityBrowsColorsScheme
    ) {
        BackHandler(showPopupMenu.value) {
            showPopupMenu.value = false
        }
        val isFavorite = remember {
            mutableStateOf<BrowsWebFavoriteBean?>(null)
        }
        LaunchedEffect(Unit) {
            withContext(Dispatchers.IO) {

                val url = tabWebViewModel.currentWebUrl.value
                if (!url.isNullOrEmpty()) {
                    isFavorite.value =
                        BrowsRoomHelper.getDao(this@SecurityBrowsTabWebActivity).getFavoriteByUrl(
                            url
                        )
                }
            }
        }
        val offsetX = with(LocalDensity.current) { 16.dp.toPx() }
        val offsetY = with(LocalDensity.current) { 11.dp.toPx() }
        Popup(offset = IntOffset(-offsetX.toInt(), offsetY.toInt()),
            alignment = Alignment.TopEnd,
            onDismissRequest = { showPopupMenu.value = false }) {
            Column(
                Modifier
                    .width(56.dp)
                    .border(1.dp, color = colorsScheme.homeTitleSpace, RoundedCornerShape(6.dp))
                    .background(color = colorsScheme.browsBg, RoundedCornerShape(6.dp))
            ) {
                Box(modifier = Modifier
                    .size(56.dp)

                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        scope.launch {

                            if (isFavorite.value != null) {
                                BrowsRoomHelper
                                    .getDao()
                                    .deleteWebFavorite(isFavorite.value!!)
                                isFavorite.value = null
                            } else {
                                isFavorite.value = tabWebViewModel.addFavorite()
                            }
                        }
                    }) {

                    Image(
                        painter = painterResource(id = if (isFavorite.value != null) drawableScheme.favorite_start else drawableScheme.favorite),
                        contentDescription = null,
                        modifier = Modifier
                            .align(Alignment.Center)
                            .size(20.dp),
                        contentScale = ContentScale.FillBounds
                    )
                }
                Box(modifier = Modifier
                    .size(56.dp)
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        finish()
                    }) {

                    Image(
                        painter = painterResource(id = drawableScheme.brows_home),
                        contentDescription = null,
                        modifier = Modifier
                            .align(Alignment.Center)
                            .size(20.dp),
                        contentScale = ContentScale.FillBounds
                    )
                }
                Box(modifier = Modifier
                    .size(56.dp)
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        SecurityBrowsHistoryActivity.start(this@SecurityBrowsTabWebActivity)
                    }) {

                    Image(
                        painter = painterResource(id = drawableScheme.history_icon),
                        contentDescription = null,
                        modifier = Modifier
                            .align(Alignment.Center)
                            .size(20.dp),
                        contentScale = ContentScale.FillBounds
                    )
                }
                Box(modifier = Modifier
                    .size(56.dp)
                    .clickable(interactionSource = remember {
                        MutableInteractionSource()
                    }, indication = rememberRipple()) {
                        if (!tabWebViewModel.currentWebUrl.value.isNullOrEmpty()) {
                            SecurityBrowsTabWebActivity.startSafari(
                                this@SecurityBrowsTabWebActivity,
                                tabWebViewModel.currentWebUrl.value!!
                            )
                        }
                    }) {

                    Image(
                        painter = painterResource(id = R.drawable.brows_safari_icon),
                        contentDescription = null,
                        modifier = Modifier
                            .align(Alignment.Center)
                            .size(20.dp),
                        contentScale = ContentScale.FillBounds
                    )
                }
            }
        }
    }


    fun f(): Boolean {
        if (this.webView?.canGoBack() == true) {
            this.webView?.goBack()
            return true
        }
        this.webView?.loadUrl("about:blank")
        return false
    }


    @Composable
    private fun BoxScope.BoxWebView(url: String) {
        Box(
            modifier = Modifier
                .fillMaxSize()
        ) {
            BrowsMyWebView(tabWebViewModel) { webView ->
                if (!webView.url.isNullOrEmpty()) {
                    return@BrowsMyWebView
                }
                this@SecurityBrowsTabWebActivity.webView = webView
                webView.loadUrl(url)

                countDownTimer?.cancel()
                countDownTimer = object : CountDownTimer(0x3B9AC9FFL, 7000L) {

                    // android.os.CountDownTimer
                    override fun onFinish() {}

                    // android.os.CountDownTimer
                    override fun onTick(v: Long) {

                        BrowsM3U8Helper.tickShowHtmlVideo(webView)
                    }
                }
                countDownTimer?.start()
                isTimerStart = true
            }
        }
    }

    override fun onPause() {
        super.onPause()
        if (isTimerStart) {
            isTimerStart = false
            countDownTimer?.cancel()
        }
    }

    override fun onResume() {
        super.onResume()
        if (!isTimerStart) {
            isTimerStart = true
            countDownTimer?.start()
        }
    }

    @Composable
    fun BottomSheetScaffoldCompose(
        rememberBottomSheetScaffoldState: BottomSheetScaffoldState,
        videoList: State<MutableList<BrowsVideoPrepare>?>,
        colorsScheme: SecurityBrowsColorsScheme,
        drawableScheme: SecurityBrowsDrawable,
        downloadSelectList: SnapshotStateList<BrowsVideoPrepare>
    ) {
        val context = LocalContext.current

        val scope = rememberCoroutineScope()



        BottomSheetScaffold(sheetPeekHeight = 0.dp,
            sheetShape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp),
            sheetContainerColor = colorsScheme.webSheetContainer,
            modifier = Modifier.zIndex(Float.MAX_VALUE),
            scaffoldState = rememberBottomSheetScaffoldState,
            sheetContent = {
                Box(modifier = Modifier.fillMaxWidth()) {
                    LazyColumn(
                        modifier = Modifier
                            .padding(horizontal = 12.dp)
                            .fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        item {
                            Column(Modifier.fillMaxWidth()) {
                                Text(
                                    text = "Select the video quality you prefer",
                                    modifier = Modifier.align(Alignment.CenterHorizontally),
                                    fontSize = 14.sp, color = colorsScheme.webSheetTitle
                                )
                                Spacer(modifier = Modifier.height(15.dp))
                            }
                        }
                        items(videoList.value ?: arrayListOf()) {
                            ItemLazy(it = it, drawableScheme, colorsScheme, downloadSelectList)
                        }
                        item {
                            Spacer(modifier = Modifier.height(70.dp))
                        }
                    }
                    Box(
                        modifier = Modifier
                            .align(Alignment.BottomCenter)
                            .fillMaxWidth()
                            .height(70.dp)
                    ) {
                        Image(
                            painter = painterResource(id = drawableScheme.sheet_video_download),
                            contentDescription = null,
                            modifier = Modifier
                                .align(
                                    Alignment.Center
                                )
                                .height(36.dp)
                                .clickable {

                                    if (downloadSelectList.isEmpty()) {
                                        Toast
                                            .makeText(
                                                context,
                                                "Please select at least one.",
                                                Toast.LENGTH_SHORT
                                            )
                                            .show()
                                    } else {
                                        for (i in downloadSelectList) {
                                            if (i.downloadWrapper.value == null) {
                                                BrowsApplication.browsMyViewModel.startDownload(
                                                    context,
                                                    i
                                                )
                                            }
                                        }

                                        Toast
                                            .makeText(
                                                context,
                                                "Added in download que.",
                                                Toast.LENGTH_SHORT
                                            )
                                            .show()

                                        if (!hasToastDoNotCloseWhenDownloading) {
                                            Toast
                                                .makeText(
                                                    context,
                                                    "Please keep the app open while downloading.",
                                                    Toast.LENGTH_SHORT
                                                )
                                                .show()
                                        }
                                        downloadSelectList.clear()
                                        scope.launch {
                                            rememberBottomSheetScaffoldState.bottomSheetState.hide()
                                        }
                                    }
                                },
                            contentScale = ContentScale.FillHeight
                        )
                    }
                }
            }) {

        }
    }


    @Composable
    private fun ItemLazy(
        it: BrowsVideoPrepare,
        drawableScheme: SecurityBrowsDrawable,
        colorsScheme: SecurityBrowsColorsScheme,
        downloadSelectList: SnapshotStateList<BrowsVideoPrepare>
    ) {
        val context = LocalContext.current
        val thumbPath = it.thumbPath.observeAsState()
        val width = it.videoWidth.observeAsState()
        val height = it.videoHeight.observeAsState()
        val duration = it.videoDuration.observeAsState()
        val fileSize = it.videoLength.observeAsState()
        val isM3U8 = it.isM3U8

        val entity = it.downloadWrapper.observeAsState()

        Box(
            Modifier
                .clip(RoundedCornerShape(10.dp))
                .fillMaxWidth()
                .height(88.dp)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    if (downloadSelectList.contains(it)) {
                        downloadSelectList.remove(it)
                    } else {
                        downloadSelectList.add(it)
                    }
                }
        ) {
            val isChoose = downloadSelectList.contains(it)
            if (isChoose) {
                Spacer(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(colorsScheme.sheetVideoChooseBg)
                )
            }
            Row(Modifier.fillMaxSize()) {
                Box(
                    Modifier
                        .padding(8.dp)
                        .fillMaxHeight()
                        .aspectRatio(110f / 72f, true)
                ) {
                    AsyncImage(
                        model = thumbPath.value,
                        contentDescription = null,
                        modifier = Modifier
                            .clip(RoundedCornerShape(12.dp))
                            .fillMaxSize(),
                        contentScale = ContentScale.Crop
                    )
                    Image(
                        painter = painterResource(id = drawableScheme.sheet_video_play),
                        contentDescription = null,
                        modifier = Modifier
                            .align(
                                Alignment.Center
                            )
                            .size(20.dp)
                    )
                    if ((duration.value ?: 0.0) > 0) {
                        val totalSeconds =
                            if (isM3U8) (duration.value ?: 0.0) else ((duration.value
                                ?: 0.0) / 1000)
                        val hours = totalSeconds / 3600
                        val minutes = (totalSeconds % 3600) / 60
                        val seconds = totalSeconds % 60
                        Text(
                            modifier = Modifier
                                .padding(7.dp)
                                .align(Alignment.BottomStart),
                            text = String.format(
                                "%02d:%02d:%02d", hours.toInt(), minutes.toInt(), seconds.toInt()
                            ),
                            fontSize = 11.sp,
                            color = colorsScheme.sheetVideoDuration
                        )
                    }
                }

                Column(Modifier.align(Alignment.CenterVertically)) {

                    Text(
                        text = it.title ?: it.getFileName(),
                        fontSize = 16.sp,
                        color = if (isChoose) colorsScheme.sheetVideoTitleChoose else colorsScheme.sheetVideoTitle,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    var text = " "
                    if (width.value != 0 && height.value != 0) {
                        text = "${width.value}X${height.value}"
                    }
                    Text(
                        text = text,
                        fontSize = 14.sp,
                        color = if (isChoose) colorsScheme.sheetVideoResolutionChoose else colorsScheme.sheetVideoResolution
                    )
                }
            }
            if (fileSize.value != null && fileSize.value!! > 0) {
                Text(
                    modifier = Modifier
                        .padding(bottom = 9.dp, end = 16.dp)
                        .align(Alignment.BottomEnd),
                    text = Formatter.formatFileSize(context, fileSize.value!!).replace(" ", ""),
                    fontSize = 14.sp,
                    color = if (isChoose) colorsScheme.sheetVideoSizeChoose else colorsScheme.sheetVideoSize
                )
            }
        }
    }

}